package com.cuckoo.cuckoo_app2.ui;

import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;

import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.cuckoo.cuckoo_app2.MyApplication;
import com.cuckoo.cuckoo_app2.R;
import com.cuckoo.cuckoo_app2.adapters.DashboadrdPlatformAdpter;
import com.cuckoo.cuckoo_app2.adapters.VipCardItemComponAdpter;
import com.cuckoo.cuckoo_app2.apiAsync.BaseCallbac;
import com.cuckoo.cuckoo_app2.apiAsync.Imp.VersionControlApiImp;
import com.cuckoo.cuckoo_app2.apiAsync.VersionControlApi;
import com.cuckoo.cuckoo_app2.dao.User;
import com.cuckoo.cuckoo_app2.dao.VipCard;
import com.cuckoo.cuckoo_app2.ui.dashboard.DashboardFragment;
import com.cuckoo.cuckoo_app2.utils.DialogUtils;
import com.google.gson.Gson;
import com.google.gson.JsonArray;
import com.google.gson.JsonObject;
import com.google.gson.reflect.TypeToken;

import java.lang.reflect.Type;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.List;

public class VipMembershipAcitvity extends AppCompatActivity {

    private RecyclerView recyclerView;
    private VipCardItemComponAdpter adpter;
    private List<VipCard> dataList = new ArrayList<>();
    private VersionControlApi versionControlApi;
    private Context context;
    private User user;
    private ViewHolder holder;
    private SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
    private Gson gson;
    private boolean isLoading = false;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_vip_membership);
        context = this;
        gson = new Gson();
        holder = new ViewHolder();
        versionControlApi = new VersionControlApiImp();

        // 初始化 RecyclerView
        recyclerView = findViewById(R.id.vip_card_item);
        recyclerView.setLayoutManager(new LinearLayoutManager(this));

        // 初始化适配器并设置给 RecyclerView
        adpter = new VipCardItemComponAdpter(this, dataList, new ButtonClickListener());
        recyclerView.setAdapter(adpter);

        this.initView();
    }

    @Override
    protected void onStart() {
        super.onStart();
        this.getData();
    }

    @Override
    protected void onStop() {
        super.onStop();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
    }


    private void initView() {
        user = MyApplication.getInstances().getUser();

        holder.vip_user_name.setText(user.getName());
        holder.vip_user_icon.setVisibility(View.GONE);
        if (user.getIsVip() == 1) {
            holder.vip_user_icon.setVisibility(View.VISIBLE);
            String endVip = sdf.format(user.getEndVip());
            String validity = "会员有效期至：" + endVip;
            holder.vip_user_validity.setText(validity);
        } else {
            holder.vip_user_validity.setText("普通会员");
        }
    }

    private void getData() {
        versionControlApi.VipListAsync(new BaseCallbac<JsonObject>() {

            @Override
            public void onSuccess(JsonObject data) {
                if (!data.get("success").getAsBoolean()) {
                    return;
                }
                JsonArray result = data.get("result").getAsJsonArray();
                List<VipCard> list = new ArrayList<>();
                VipCard vipCard;
                for (int i = 0; i < result.size(); i++) {
                    vipCard = gson.fromJson(result.get(i), VipCard.class);
                    list.add(vipCard);
                }
                dataList = list;
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        updateRecyclerViewData();
                    }
                });
            }

            @Override
            public void onFailure(String errorMessage) {
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        DialogUtils.showToast(context, errorMessage);
                    }
                });
            }
        });
    }

    public void clearRecyclerViewData() {
        if (adpter != null) {
            adpter.clearData(); // 调用适配器的方法来清空数据
        }
    }

    /**
     * 更新页面
     */
    public void updateRecyclerViewData() {
        if (adpter != null) {
            adpter.updateData(dataList); // 调用适配器的方法来更新数据
        }
    }

    public class ButtonClickListener {

        public void onEnter(VipCard vipCard) {
            runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    String title = "【" + vipCard.getTitle() + "】提示";
                    DialogUtils.showAlertDialog(context, title, "确认要购买此会员卡吗？", new DialogInterface.OnClickListener() {

                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                            buyVipCard(vipCard);
                        }

                    }, new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                            DialogUtils.hideCurrentDialog();
                        }
                    });
                }
            });
        }
    }

    /**
     * 下单购买会员卡
     */
    public void buyVipCard(VipCard vipCard) {
        if (isLoading) {
            return;
        }
        isLoading = true;
        versionControlApi.BuyVipCardAsync(vipCard.getId(), new BaseCallbac<JsonObject>() {

            @Override
            public void onSuccess(JsonObject data) {
                isLoading = false;
                runOnUiThread(() -> {
                    if (!data.get("success").getAsBoolean()) {
                        DialogUtils.showToast(context, data.get("message").getAsString());
                        return;
                    }
                    String message = data.get("message").getAsString();
                    String url = data.get("result").getAsString();
                    Log.i("TEST", url);
                    // 跳转url
                    Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(url));
                    startActivity(intent);

                    // 提示
                    DialogUtils.showConfirmDialog(context, "系统提示", message, new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                            DialogUtils.hideCurrentDialog();
                        }
                    });
                });
            }

            @Override
            public void onFailure(String errorMessage) {
                isLoading = false;
                runOnUiThread(() -> {
                    DialogUtils.showToast(context, errorMessage);
                });
            }
        });
    }


    /**
     * 获取相应的ID
     */
    class ViewHolder {
        TextView vip_user_name;
        ImageView vip_user_icon;
        TextView vip_user_validity;

        public ViewHolder() {
            vip_user_name = findViewById(R.id.vip_user_name);
            vip_user_icon = findViewById(R.id.vip_user_icon);
            vip_user_validity = findViewById(R.id.vip_user_validity);

        }
    }


}
